package com.zxmr.asyn;

import java.io.IOException;

import com.zxmr.action.Request;

/*
 *  this class provide asyn request interface. user need to invoke markSuccess or markFailed
 *  when request success and failed
 */
public abstract class AsynRequest implements CallBack{

	boolean success = true;
	int transaction = 0;
	int requestID = -1;
	
	// time of timeout in ms
	int timeout = 0;
	
	Request request;
	
	public int getTimeout() {
		return timeout;
	}
	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}
	private void register()
	{
		success = true;
		requestID = -1;
		requestID = AsynRequestRegister.register(this);
	}

	public int getRequestID()
	{
		return this.requestID;
	}
	public int getTransaction()
	{
		return this.transaction;
	}
	
	// if request already timeout then return false
	public boolean markSuccess()
	{
		synchronized(this)
		{
			// if the request is already timeout then return false
			if(!success)return false;
			// else need to increase transaction and remove the register
			transaction++;
			
			AsynRequestRegister.remove(requestID);
			return true;
		}
	}
	public boolean markFailed(int transactionID)
	{
		synchronized(this)
		{
			// if the transaction is same and current success is true then it
			// means that the request is not success at the time
			if(transactionID == transaction && success)
			{
				transaction++;
				success = false;
				
				AsynRequestRegister.remove(requestID);
				return true;
			}
			return false;
		}
	}
	public Request getRequest() {
		return request;
	}

	public void setRequest(Request request) {
		this.request = request;
	}
	public boolean send(String sourceQueue,String targetQueue)
	{
		this.register();
		request.setId(String.valueOf(this.getRequestID()));
		boolean result = false;
		try {
			result = request.send(sourceQueue, targetQueue);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(!result)this.markFailed(transaction);
		
		return result;
	}
	public abstract void requestTimeOut();
}
